package nc.pub.cgdd.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import nc.bs.framework.common.NCLocator;
import nc.bs.scmpub.query.SCMBillQuery;
import nc.config.bcsi.FileUtil;
import nc.fi.arap.pubutil.RuntimeEnv;
import nc.itf.uap.pf.IPfExchangeService;
import nc.itf.uap.pf.IplatFormEntry;
import nc.pub.cgdd.utils.util.JdbcUtil;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.model.entity.bill.AbstractBill;
import nccloud.openapi.pu.m21.PuOrderResource;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONString;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.IntStream;

/**
 * 中国长城采购订单生成采购订单订单工具类
 * @author lenovo
 */
public class GeneratOrderUtils {
 public  static final  String PO="/template/poorder.json";
 public  static final  String currentbilltype="CGDDO";
 private PuOrderResource ar =new PuOrderResource();
 private  HashMap<String,Object> param=null;
 private static GeneratOrderUtils instance=new GeneratOrderUtils();
 
 public HashMap<String, Object> getParam() {
	return param;
}
public void setParam(HashMap<String, Object> param) {
	this.param = param;
}
private GeneratOrderUtils() {
	 
 }
 public static GeneratOrderUtils getInstance() {
	 return instance;
 }
 
 
 
 public OrderVO[]  excute(AggregatedValueObject[]vo) throws BusinessException {
	 param=new HashMap<String,Object> ();
	 ArrayList<Map<String, Object>> excuteAssemble = assembleJson(vo);
		JSONString save = ar.save(excuteAssemble);
		JSONObject parseObject = JSONObject.parseObject(save.toJSONString());
		Boolean boolean1 = "采购订单保存成功".equals(parseObject.getString("message"))&&parseObject.getBoolean("success")&&"1".equals(parseObject.getString("code"));
		if(!boolean1) {
			throw new BusinessException("生成采购订单时异常:"+parseObject.getString("message")+"//r//n errorStack:"+parseObject.getString("message"));
		}
		JSONArray jsonArray = parseObject.getJSONArray("data");
		String hids = jsonArray.getJSONObject(0).getJSONObject("pu.po_order").getString("pk_order");
		param.put("pk_order", hids);
		SCMBillQuery<OrderVO> queryTool = new SCMBillQuery(OrderVO.class); 
		OrderVO[] orderVOs = (OrderVO[])queryTool.queryVOByIDs(new String[] {hids});
		IplatFormEntry iplat = NCLocator.getInstance().lookup(IplatFormEntry.class);
		OrderVO[] saveobj = (OrderVO[]) iplat.processAction("APPROVE","21", null, orderVOs[0], null, null);
		return orderVOs;
 }
 /**
  * 执行JSON转化
  * @param vo
  * @return
  * @throws BusinessException
  */
 public  ArrayList<Map<String, Object>> excuteAssemble(AggregatedValueObject[]vo) throws BusinessException {

		return assembleJson(vo);
 }
/**
 * 获取JSON模板
 * @param templatePath
 * @return
 */
 private  String  getTemplate(String templatePath) {
	 String filePath=RuntimeEnv.getNCHome()+templatePath;
		String readStreamByBytes = FileUtil.readStreamByBytes(filePath);
		return readStreamByBytes;
 }
 
 /**
  * 拉去单据转换规则转换后数据
  * 
  * @param vo
  * @param srcbilltyap
  * @param tagbilltyep
  * @return
  * @throws BusinessException
  */
 private  AggregatedValueObject getChageData(AggregatedValueObject vo,String srcbilltyap,String tagbilltyep) throws BusinessException {
	 IPfExchangeService transferService = NCLocator.getInstance().lookup(IPfExchangeService.class);
	 AggregatedValueObject runChangeData = transferService.runChangeData(srcbilltyap, tagbilltyep, vo, null);
	return runChangeData;
 }
 /**
  * 组装转换Json 
  * @param vo
  * @return
  * @throws BusinessException
  */
 private  ArrayList<Map<String, Object>> assembleJson(AggregatedValueObject[]vo) throws BusinessException{
	 ArrayList<Map<String,Object>> po = new ArrayList();
	  Gson gson = new Gson();
      Type type = new TypeToken<Map<String, Object>>(){}.getType();
	 for (AggregatedValueObject poOrder : vo) {
			 String [] bodysName=new String[] {"po_order_b"};
			 String template = getTemplate(PO);
			 JSONObject assembleJson = assembleJson(poOrder, template,"21","po_order",bodysName);
		        Map<String, Object> map = gson.fromJson(assembleJson.toString(), type);
			 po.add(map);
		 }
	return po;
	 
 }
 /**
  * 组件JSON执行
  * @param poOrder
  * @param template
  * @param tagBilltype
  * @return
  * @throws BusinessException
  */
private JSONObject assembleJson(AggregatedValueObject poOrder,String template,String tagBilltype,String tablename,String ...bodysName) throws BusinessException {
	JSONObject tempJson =JSONObject.parseObject(template).getJSONArray("data").getJSONObject(0);
	CircularlyAccessibleValueObject contractParent = poOrder.getParentVO();
	JSONObject headVo=tempJson.getJSONObject(tablename);
	AbstractBill chageData = (AbstractBill)getChageData(poOrder,currentbilltype,tagBilltype);
	CircularlyAccessibleValueObject parentVO = chageData.getParentVO();
//	String org = String.valueOf(contractParent.getAttributeValue("pk_org"));
	headVo.put("vtrantypecode", "21-Cxx-16");
	assembleHead(parentVO,headVo);
	headVo.put("pk_supplier", contractParent.getAttributeValue("pk_supplier"));
	String pk_dept = JdbcUtil.queryColumn("org_dept_v", "pk_dept", "pk_vid", String.valueOf(contractParent.getAttributeValue("pk_dept_v")));
	headVo.put("pk_dept", pk_dept);	
	headVo.put("vbillcode", null);
	// 来源单据类型
	headVo.put("csourcetypecode", currentbilltype);
	//来源单据id
	headVo.put("csourceid", contractParent.getPrimaryKey());


	//处理表体
	tempJson.put(tablename, headVo);
	for (String bodyName : bodysName) {
		JSONArray jsonArray = tempJson.getJSONArray(bodyName);
		chageData.getTableCodes();
		CircularlyAccessibleValueObject[] childrenVO = chageData.getTableVO(bodyName.replace("po", "pk"));
//		CircularlyAccessibleValueObject[] childrenVO = poOrder.getChildrenVO();
		assembleBodys(childrenVO, jsonArray,headVo,poOrder);

	}
	return tempJson;
}
//表头字段处理
private JSONObject  assembleHead(CircularlyAccessibleValueObject parentVO,JSONObject resutl) {
	Arrays.asList(parentVO.getAttributeNames()).stream().forEach((item)->{
		Object attributeValue = parentVO.getAttributeValue(item);
		if(!ObjectUtils.isEmpty(attributeValue)&&StringUtils.isNotBlank(attributeValue.toString())) {
				resutl.put(item, attributeValue.toString());
		}
	});
	return resutl;
}
/**
 *  表体的转换
 * @param bodys  通过单据转换规则的 数据
 * @param resutl 通过模板生成的json 结果 数据
 * @return
 */
private JSONArray  assembleBodys(CircularlyAccessibleValueObject[] bodys,JSONArray resutl,JSONObject headVo,AggregatedValueObject poOrder)  {
	if(ObjectUtils.isEmpty(bodys)) {
		return resutl;
	}
//	AggPurchaseOrderMasterVO order= new AggPurchaseOrderMasterVO();
//	PurchaseOrderVO[] children=new PurchaseOrderVO[bodys.length];
//	if(poOrder instanceof AggPurchaseOrderMasterVO) {
//		order =(AggPurchaseOrderMasterVO)poOrder;
//		children = (PurchaseOrderVO[]) order.getChildren(nc.vo.cgdd.PurchaseOrderVO.class);
//	}
	 
	String[] except =new String[] {"pk_psfinanceorg","pk_psfinanceorg_v","pk_arrvstoorg"};
	List<String> asList = Arrays.asList(except);
		for (int i = 0; i < bodys.length; i++) {
			//获取采购订单生成的行数据
			CircularlyAccessibleValueObject body=bodys[i];
//			PurchaseOrderVO purchaseOrderVO = children[i];
		JSONObject jsonObject = (JSONObject) resutl.getJSONObject(0).clone();
//		Object materia_name = bodys[0].getAttributeValue("materia_name");
//		Object materia_code = bodys[0].getAttributeValue("materia_code");
//		jsonObject.put("pk_material", materia_code==null?materia_name:materia_code);
		  String[] keyNames = body.getAttributeNames();
		  IntStream.range(0, keyNames.length).forEach((index)->{
			try {
				String	pk_arrvstoorg ="";
				//字段名称
				String item =keyNames[index];
				//字段值
			Object attributeValue = body.getAttributeValue(item);
			if(!ObjectUtils.isEmpty(attributeValue)&&StringUtils.isNotBlank(attributeValue.toString())&&!asList.contains(item)) {
				jsonObject.put(item, attributeValue.toString());
			}
			
				if("pk_arrvstoorg_v".equals(item)) {
					 pk_arrvstoorg = JdbcUtil.queryColumn("org_stockorg", "pk_stockorg", "pk_vid",String.valueOf(attributeValue));
					//所属财务组织
					String pk_financeorg= JdbcUtil.queryColumn("org_stockorg_v", "pk_financeorg", "pk_stockorg", pk_arrvstoorg);
					String pk_financeorg_v= JdbcUtil.queryColumn("org_financeorg", "pk_vid", "pk_financeorg", pk_financeorg);
					jsonObject.put("pk_arrvstoorg",pk_arrvstoorg);
					//结算组织
					jsonObject.put("pk_psfinanceorg", pk_financeorg);
					jsonObject.put("pk_psfinanceorg_v", pk_financeorg_v);
					//应付组织
					jsonObject.put("pk_apfinanceorg", pk_financeorg );
					jsonObject.put("pk_apfinanceorg_v", pk_financeorg_v );
					}
				//计算生成采购订单的数量
				if("nastnum".equals(item)) {
					UFDouble nastnum = new UFDouble(String.valueOf(attributeValue).equals("null")?"0":String.valueOf(attributeValue));
					//长城采购单上的累计入库数量
//					 UFDouble quantity = purchaseOrderVO.getCumulative_quantity();
//						UFDouble cumulative_quantity = quantity==null?new UFDouble(0):quantity;
//						nastnum=nastnum.sub(cumulative_quantity);
					jsonObject.put(item, nastnum.toString());
				}
			} catch (BusinessException e) {
				
			}
//			jsonObject.put("pk_psfinanceorg_v", body.getAttributeValue("pk_psfinanceorg_v"));
		});
		// 来源单据类型
		jsonObject.put("csourcetypecode", currentbilltype);
		//来源单据id
		jsonObject.put("csourceid", headVo.get("csourceid"));
		
		resutl.add(jsonObject);
	}
	resutl.remove(0);

	return resutl;
}
//采购订单执行诗审核
public JSONString excuteApprovel(String pk) {
	JSONString approve = ar.approve(new String[] {pk});
	return approve;
	
}



}
